<template>
  <div class="page-wrapper">
    <div class="app-container">
      <!-- 页面头部 -->
      <PageHeader back-text="返回" back-type="back" :title="projectInfo.proName || '加载中...'" />

      <!-- 项目详情卡片 -->
      <ProjectDetail :project-info="projectInfo" :loading="projectLoading" />

      <!-- 成本统计卡片 -->
      <el-card class="mb-6 statistics-card">
        <template #header>
          <div class="statistics-header">
            <el-icon class="statistics-icon">
              <Money />
            </el-icon>
            <span class="statistics-title">项目成本消耗统计汇总</span>
          </div>
        </template>
        <div class="statistics-grid">
          <div class="stat-item">
            <div class="stat-label">人员成本总计</div>
            <div class="stat-value staff-cost">{{ formatAmount(totalStatistics.staffCost) }}元</div>
            <div class="stat-desc">项目人员投入成本</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">差旅成本总计</div>
            <div class="stat-value travel-cost">{{ formatAmount(totalStatistics.travelCost) }}元</div>
            <div class="stat-desc">出差交通住宿成本</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">办公成本总计</div>
            <div class="stat-value office-cost">{{ formatAmount(totalStatistics.officeCost) }}元</div>
            <div class="stat-desc">办公用品设备成本</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">总消耗成本</div>
            <div class="stat-value total-cost">{{ formatAmount(totalStatistics.totalCost) }}元</div>
            <div class="stat-desc">所有成本项目合计</div>
          </div>
        </div>
      </el-card>

      <!-- 成本消耗信息卡片 -->
      <el-card class="box-card cost-card mb-6">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="card-header-left">
              <span class="title">成本消耗信息</span>
            </div>
            <div class="flex items-center" style="gap: 12px">
              <ProjectStatusDisplay label="成本消耗审核状态" :status-options="approval_commit_status"
                :status-value="costAuditStatusValue" />
              <el-button type="primary" icon="Refresh" @click="loadCostList"
                :loading="costTableLoading">刷新</el-button>
            </div>
          </div>
        </template>

        <!-- 成本消耗信息表格 -->
        <div class="cost-container">
          <el-table v-loading="costTableLoading" :data="costList" border style="width: 100%" row-key="id" class="cost-table">
            <!-- 项目名称 -->
            <el-table-column label="项目名称" align="center" min-width="200" fixed="left" :show-overflow-tooltip="true">
              <template #default="scope">
                <span>{{ scope.row.proName || '-' }}</span>
              </template>
            </el-table-column>

            <!-- 项目执行总裁 -->
            <el-table-column label="项目执行总裁" align="center" min-width="150" fixed="left" :show-overflow-tooltip="true">
              <template #default="scope">
                <span>{{ scope.row.proPresidentsName || '-' }}</span>
              </template>
            </el-table-column>

            <!-- 项目负责人 -->
            <el-table-column label="项目负责人" align="center" min-width="150" fixed="left" :show-overflow-tooltip="true">
              <template #default="scope">
                <span>{{ scope.row.proLeadersName || '-' }}</span>
              </template>
            </el-table-column>

            <!-- 人员成本 -->
            <el-table-column label="人员成本" align="center" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.staffCost">{{ formatAmount(scope.row.staffCost) }}元</span>
                <span v-else class="text-gray-400">0.00元</span>
              </template>
            </el-table-column>

            <!-- 差旅成本 -->
            <el-table-column label="差旅成本" align="center" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.travelCost">{{ formatAmount(scope.row.travelCost) }}元</span>
                <span v-else class="text-gray-400">0.00元</span>
              </template>
            </el-table-column>

            <!-- 办公成本 -->
            <el-table-column label="办公成本" align="center" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.officeCost">{{ formatAmount(scope.row.officeCost) }}元</span>
                <span v-else class="text-gray-400">0.00元</span>
              </template>
            </el-table-column>

            <!-- A1成本 -->
            <el-table-column label="A1成本" align="center" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.a1Cost">{{ formatAmount(scope.row.a1Cost) }}元</span>
                <span v-else class="text-gray-400">0.00元</span>
              </template>
            </el-table-column>

            <!-- A2成本 -->
            <el-table-column label="A2成本" align="center" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.a2Cost">{{ formatAmount(scope.row.a2Cost) }}元</span>
                <span v-else class="text-gray-400">0.00元</span>
              </template>
            </el-table-column>

            <!-- 其他成本 -->
            <el-table-column label="其他成本" align="center" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.otherCost">{{ formatAmount(scope.row.otherCost) }}元</span>
                <span v-else class="text-gray-400">0.00元</span>
              </template>
            </el-table-column>

            <!-- 总成本 -->
            <el-table-column label="总成本" align="center" min-width="180">
              <template #default="scope">
                <span style="color: #f56c6c; font-weight: bold">{{ formatAmount(scope.row.totalCost) }}元</span>
              </template>
            </el-table-column>

            <!-- 创建时间 -->
            <el-table-column label="更新时间" align="center" prop="updateTime" min-width="150">
              <template #default="scope">
                {{ scope.row.updateTime ? parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}
              </template>
            </el-table-column>

            <!-- 备注 -->
            <el-table-column label="备注" align="center" width="300">
              <template #default="scope">
                <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
                  <span class="text-overflow">{{ scope.row.remark || '-' }}</span>
                </el-tooltip>
              </template>
            </el-table-column>

            <template #empty>
              <el-empty description="暂无成本消耗数据" />
            </template>
          </el-table>

          <!-- 底部信息组件 -->
          <ProjectBottomInfo :project-list="costList" />
        </div>
      </el-card>

      <!-- 审核操作组件 -->
      <AuditAction :loading="auditLoading" @audit="handleAuditAction" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getProDetail } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { listProCostConsume } from '@/api/project/cost/consume';
import type { ProCostConsumeVO } from '@/api/project/cost/consume/types';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import ProjectBottomInfo from '@/views/project/components/ProjectBottomInfo.vue';
import AuditAction from '@/components/AuditAction/index.vue';
import { audit } from '@/api/other/approval/index';
import type { ApprovalAuditBo } from '@/api/other/approval/types';
import { formatAmount } from '@/components/NumberInput';
import { parseTime } from '@/utils/ruoyi';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { approval_commit_status } = toRefs<any>(proxy?.useDict('approval_commit_status'));

// 项目信息
const projectInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);
const costAuditStatusValue = computed(() => {
  const anyInfo = projectInfo.value as any;
  return (anyInfo && anyInfo.consumeAuditStatus) ?? '0';
});

// 成本消耗列表
const costList = ref<ProCostConsumeVO[]>([]);
const costTableLoading = ref(false);

// 统计数据
const totalStatistics = ref({
  staffCost: 0,
  travelCost: 0,
  officeCost: 0,
  a1Cost: 0,
  a2Cost: 0,
  otherCost: 0,
  totalCost: 0
});

// 审核相关
const auditLoading = ref(false);

// 项目ID
const proId = ref<number>(Number(route.params.proId));

/**
 * 获取项目信息
 */
const getProjectDetail = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  try {
    projectLoading.value = true;
    const res = await getProDetail(proId);
    projectInfo.value = res.data || {};
  } catch (error) {
    console.error('获取项目信息失败:', error);
    ElMessage.error('获取项目信息失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 获取成本消耗列表数据
 */
const loadCostList = async () => {
  try {
    costTableLoading.value = true;
    const res = await listProCostConsume(proId.value);
    costList.value = res.data || [];
    // 计算统计数据
    calculateTotalStatistics();
  } catch (error) {
    console.error('获取成本消耗列表失败:', error);
    ElMessage.error('获取成本消耗列表失败');
  } finally {
    costTableLoading.value = false;
  }
};

/**
 * 安全转换金额数值
 */
const safeNumber = (value: any): number => Number(value) || 0;

/**
 * 计算总统计数据
 */
const calculateTotalStatistics = () => {
  const totals = costList.value.reduce(
    (acc, item) => ({
      staffCost: acc.staffCost + safeNumber(item.staffCost),
      travelCost: acc.travelCost + safeNumber(item.travelCost),
      officeCost: acc.officeCost + safeNumber(item.officeCost),
      a1Cost: acc.a1Cost + safeNumber(item.a1Cost),
      a2Cost: acc.a2Cost + safeNumber(item.a2Cost),
      otherCost: acc.otherCost + safeNumber(item.otherCost),
      totalCost: acc.totalCost + safeNumber(item.totalCost)
    }),
    { staffCost: 0, travelCost: 0, officeCost: 0, a1Cost: 0, a2Cost: 0, otherCost: 0, totalCost: 0 }
  );
  totalStatistics.value = totals;
};

// 审核提交
const handleAuditAction = (data: { status: string; idea: string }) => {
  auditLoading.value = true;
  const auditData: ApprovalAuditBo = {
    businessId: projectInfo.value.id as any,
    businessType: 'PROJECT-CONSUME-AUDIT',
    status: data.status,
    idea: data.idea
  } as ApprovalAuditBo;

  audit(auditData)
    .then(() => {
      ElMessage.success('审核成功');
      router.push('/index');
    })
    .catch(() => {
      auditLoading.value = false;
    });
};

onMounted(() => {
  getProjectDetail();
  loadCostList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 统计卡片样式 */
.statistics-card {
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
  border: 1px solid #e1ecff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.08);
  border-radius: 8px;
}

.statistics-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-color-primary);
  font-weight: 600;
}

.statistics-icon {
  font-size: 20px;
  color: var(--el-color-primary);
}

.statistics-title {
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px 16px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e1ecff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.12);
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
  line-height: 1.2;
}

.stat-desc {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  line-height: 1.4;
}

.staff-cost {
  color: #10b981;
}

.travel-cost {
  color: #f59e0b;
}

.office-cost {
  color: var(--el-color-primary);
}

.total-cost {
  color: #f56c6c;
}

.cost-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

/* 卡片头部样式 */
.card-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.cost-container {
  position: relative;
}

.text-overflow {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.text-gray-400 {
  color: #c0c4cc;
}

.cost-table {
  width: 100%;
}

.cost-table :deep(.el-table__cell) {
  padding: 8px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .card-header .left {
    flex-wrap: wrap;
    gap: 8px;
  }

  /* 统计卡片响应式 */
  .statistics-grid {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px 0;
  }

  .stat-item {
    padding: 16px 12px;
  }

  .stat-value {
    font-size: 20px;
  }

  .stat-label {
    font-size: 13px;
  }

  .stat-desc {
    font-size: 11px;
  }
}
</style>
